package com.egreen.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egreen.common.States;
import com.egreen.common.pojo.DTO.user.validation.ValidateCodeDTO;
import com.egreen.common.pojo.entity.user.User;
import com.egreen.common.pojo.entity.user.UserLoginAccount;
import com.egreen.common.pojo.entity.user.UserValidation;
import com.egreen.common.serviceapi.system.VerificationCodeAPI;
import com.egreen.common.serviceapi.user.IUserServiceApi;
import com.egreen.user.exceptions.UserException;
import com.egreen.user.dao.UserDao;
import com.egreen.user.dao.UserLoginAccountDao;
import com.egreen.user.dao.UserValidationDao;
import com.egreen.user.service.IUserValidationService;
import com.egreen.user.utils.UserUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @Author: lyy
 * @Version: 1.0
 * @JDK-version: 1.8
 * @Date: 2022/7/21 16:00
 * @Description:
 */
@Service
@Lazy
public class UserValidationServiceImpl extends ServiceImpl<UserValidationDao, UserValidation> implements IUserValidationService {
    @Autowired
    UserDao userDao;
    @Autowired
    UserLoginAccountDao loginAccountDao;
    @Autowired
    UserValidationDao validationDao;
    @Autowired
    UserUtil util;
    @DubboReference
    VerificationCodeAPI verificationCodeAPI;
    @DubboReference
    IUserServiceApi userServiceApi;

    @Override
    public User validateCode(ValidateCodeDTO validateCodeDTO) {
        QueryWrapper wrapper = new QueryWrapper();
        String stateOfLoginKey = "";
        String loginKey = validateCodeDTO.getLoginKey();
        //判断用户是否使用手机号登录
        if (util.isNumeric(loginKey)) {
            wrapper.eq("phone", validateCodeDTO.getLoginKey());
            stateOfLoginKey = "phone";
        } else {
            wrapper.eq("email", validateCodeDTO.getLoginKey());
            stateOfLoginKey = "email";
        }

        //获取登录账户id，通过该信息获取用户验证码账户id
        UserLoginAccount loginAccount = loginAccountDao.selectOne(wrapper);
        if (loginAccount == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "用户不存在");
        }

        Long loginAccountId = loginAccount.getId();
        wrapper.clear();
        wrapper.eq(loginAccountId != null, "login_account_id", loginAccountId);
        User user = userDao.selectOne(wrapper);

        //若用户注销或不存在
        if (user == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "用户不存在");
        }

        //获取验证码id后通过id查找账户并验证验证码
        String smsCode = userServiceApi.sendValidCodeSms(loginAccount.getPhone());
        String emailCode = userServiceApi.sendValidCodeSms(loginAccount.getEmail());
        verificationCodeAPI.addVerificationCode(loginAccount.getId(),smsCode);
        verificationCodeAPI.addVerificationCode(loginAccount.getId(),emailCode);
        String validCode = "phone".equals(stateOfLoginKey) ? smsCode : emailCode;
        if (!verificationCodeAPI.getVerificationCode(loginAccount.getId()).equals(validCode)){
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "验证码错误");
        }
        return user;
    }

    @Override
    public void sendEmailForLogin(String email) {
        if (email.isEmpty()) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "邮箱不能为空");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("email", email);
        UserLoginAccount loginAccount = loginAccountDao.selectOne(wrapper);
        if (loginAccount == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "该邮箱尚未绑定");
        }
        wrapper.clear();
        wrapper.eq("login_account_id", loginAccount.getId());
        User user = userDao.selectOne(wrapper);

        //获取发送的验证码
        String emailCode = userServiceApi.sendValidCodeSms(loginAccount.getEmail());
        verificationCodeAPI.addVerificationCode(loginAccount.getId(),emailCode);
//        String code = util.sendValidEMail(email);
//        validationDao.updateById(validationDao.selectById(user.getValidationId()).setEmailCode(code));

    }

    @Override
    public void sendSmsForLogin(String phone) {
        if (phone.isEmpty()) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "手机号不能为空");
        }
        if (!util.isNumeric(phone)) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "手机号格式不正确");
        }


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        UserLoginAccount loginAccount = loginAccountDao.selectOne(wrapper);
        if (loginAccount == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "该手机号尚未注册");
        }
        wrapper.clear();
        wrapper.eq("login_account_id", loginAccount.getId());
        User user = userDao.selectOne(wrapper);

        //获取发送的验证码
        String smsCode = userServiceApi.sendValidCodeSms(loginAccount.getPhone());
        verificationCodeAPI.addVerificationCode(loginAccount.getId(),smsCode);
//        String code = util.sendValidSms(phone);
//        validationDao.updateById(validationDao.selectById(user.getValidationId()).setPhoneCode(code));
    }

    @Override
    public void sendEmail(int userId) {
        User user = userDao.selectById(userId);

        //通过用户id查找到用户并通过用户查找其登录账户里的邮箱信息
        String email = loginAccountDao.selectById(userDao.selectById(userId).getLoginAccountId()).getEmail();
        if (email == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "邮箱未绑定");
        }

        //获取发送的验证码
        String emailCode = userServiceApi.sendValidCodeSms(email);
        verificationCodeAPI.addVerificationCode(user.getId(),emailCode);
//        String code = util.sendValidEMail(email);
//        validationDao.updateById(validationDao.selectById(user.getValidationId()).setEmailCode(code));
    }

    @Override
    public void sendSms(int userId) {
        User user = userDao.selectById(userId);

        //通过用户id查找到用户并通过用户查找其登录账户里的邮箱信息
        String phone = loginAccountDao.selectById(user.getLoginAccountId()).getPhone();
        if (phone == null) {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "用户不存在");
        }

        //获取发送的验证码
        String emailCode = userServiceApi.sendValidCodeSms(phone);
        verificationCodeAPI.addVerificationCode(user.getId(),emailCode);
//        String code = util.sendValidSms(phone);
//        validationDao.updateById(validationDao.selectById(user.getValidationId()).setPhoneCode(code));
    }
}
